﻿using System;
using System.Collections.Generic;
using System.Text;
using NExt.Handler.Base.Default;
using System.Web;
using System.IO;
using NExt.Handler.Base.Common.Manager;
using System.Reflection;

namespace NExt.Handler.Component.Default.JsSerialize
{
    internal class StaticContentBuilder: IContentBuilder
    {
        private const string STATIC_RESOURCE_POSTFIX = "Static.js";

        public string Build(HttpContext context)
        {
            string assemblyName = Path.GetFileNameWithoutExtension(context.Request.Path);
            Assembly assembly = AssemblyManager.GetAssembly(assemblyName);

            string content = BuildContent(assembly);
            return content;
        }

        private string BuildContent(Assembly assembly)
        {
            string[] resourceNames = assembly.GetManifestResourceNames();
            List<string> resourceNameList = new List<string>(resourceNames);
            resourceNameList.Sort();
            StringBuilder stringBuilder = new StringBuilder();

            foreach (string resourceName in resourceNameList)
            {
                bool isValid = IsValidResource(resourceName);
                if (!isValid)
                    continue;

                string resourceContent = BuildResourceContent(assembly, resourceName);
                stringBuilder.AppendLine(resourceContent);
            }

            string content = stringBuilder.ToString();
            return content;
        }

        private bool IsValidResource(string resourceName)
        {
            return resourceName.EndsWith(STATIC_RESOURCE_POSTFIX);
        }

        private string BuildResourceContent(Assembly assembly, string resourceName)
        {
            Stream stream = assembly.GetManifestResourceStream(resourceName);
            StreamReader streamReader = new StreamReader(stream);
            string content = streamReader.ReadToEnd();
            return content;
        }
    }
}
